<!--新建固件-->
<template>
  <el-dialog
    title="新建固件"
    :visible.sync="dialogVisible"
    width="628px"
    :before-close="handleClose"
    :close-on-click-modal="false">
    <el-form ref="form" :rules="rules" :model="form" label-width="160px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="固件名称" prop="name">
            <template #label>
              <span>固件名称</span>&nbsp;
              <el-tooltip content="仅用于管理固件，不对外显示" placement="top">
                <i class="iconfont icon-wenhao"></i>
              </el-tooltip>
            </template>
            <el-input
              v-model="form.name"
              class="name-input"
              maxlength="32"
              show-word-limit
              placeholder="请输入固件名称"></el-input>
          </el-form-item>
          <el-form-item label="固件类型" prop="type">
            <template #label>
              <span>固件类型</span>&nbsp;
              <el-tooltip placement="top">
                <template #content>
                  <p>①MCU SDK开发上传MCU固件时建议选择MCU固件;</p>
                  <p>②其他开发方式，主通讯固件请选择'模组固件;</p>
                  <p>③如果模组固件被占用，可以根据自己模组通讯类型选择;</p>
                  <p>④如果固件类型置灰不可选，请查看是否有相同类型的固件;</p>
                </template>
                <i class="iconfont icon-wenhao"></i>
              </el-tooltip>
            </template>
            <el-select v-model="form.type" placeholder="请选择">
              <el-option
                v-for="item in firmwareTypeOptions"
                :key="item.type"
                :label="item.name"
                :value="item.type">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="升级通道号" prop="upgradeChannel">
            <template #label>
              <span>升级通道号</span>&nbsp;
              <el-tooltip placement="top">
                <template #content>
                  用于固件OTA对应升级，需要将通道号写入固件。(固件类型为模组固件、蓝牙固件、Zigbee固件、MCU固件已经写好)
                </template>
                <i class="iconfont icon-wenhao"></i>
              </el-tooltip>
            </template>
            <el-select v-model="form.upgradeChannel" placeholder="请选择">
              <el-option
                v-for="item in upgradeChannelOptions"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="自定义编号" prop="customNumbering">
            <template #label>
              <span>自定义编号</span>&nbsp;
              <el-tooltip placement="top">
                <template #content>
                  用于集中器等同一个PID设备内由于接入设备品牌不一致需要不同固件的设备使用，可不填。不填则根据默认方式进行填充。默认为0，即为常规通道
                </template>
                <i class="iconfont icon-wenhao"></i>
              </el-tooltip>
            </template>
            <el-input
              v-model="form.customNumbering"
              placeholder="请输入自定义编号"></el-input>
          </el-form-item>
          <el-form-item label="固件升级超时时间" prop="timeoutTime">
            <template #label>
              <span>固件升级超时时间</span>&nbsp;
              <el-tooltip content="用于规定OTA等待时间，超时判定为升级失败，可根据固件包大小和用户体验适当调整" placement="top">
                <i class="iconfont icon-wenhao"></i>
              </el-tooltip>
            </template>
            <el-input v-model="form.timeoutTime" type="number" max="1800" min="1" placeholder="请输入1~1800">
              <template slot="append">秒</template>
            </el-input>
          </el-form-item>
          <el-form-item label="单次超时时长" prop="singleTimeout">
            <template #label>
              <span>单次超时时长</span>&nbsp;
              <el-tooltip content="1-120分钟" placement="top">
                <i class="iconfont icon-wenhao"></i>
              </el-tooltip>
            </template>
            <el-input v-model="form.singleTimeout" type="number" max="120" min="1" placeholder="请输入">
              <template slot="append">秒</template>
            </el-input>
          </el-form-item>
          <el-form-item label="备注说明" prop="remarks">
            <el-input
              v-model="form.remarks"
              type="textarea"
              maxlength="200"
              show-word-limit
              placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="固件版本" prop="version">
            <template #label>
              <span>固件版本</span>&nbsp;
              <el-tooltip placement="top">
                <template #content>
                  <p>①版本号根据 小数点(.) 分割，转成int 数组，依次顺序比较数组里的 int数字，数字大则版本号大;</p>
                  <p>②若数组的int数字均相同，则比较两个数组的长度，长度长的版本号大长度也相等的则两个版本号相等;</p>
                </template>
                <i class="iconfont icon-wenhao"></i>
              </el-tooltip>
            </template>
            <el-input
              v-model="form.version"
              class="name-input"
              maxlength="32"
              show-word-limit
              placeholder="版本号格式为xx.xx.xx，如1.0.0"></el-input>
          </el-form-item>
          <el-form-item label="关键版本" prop="criticalVersionFlag">
            <template #label>
              <span>关键版本</span>&nbsp;
              <el-tooltip content="内容同原创建新固件中“关键版本为不可越过的版本，即当设定某个版本为关键版本后，即使发布了新的固件老固件也必须升级为关键版本，才可继续升级为最新版本" placement="top">
                <i class="iconfont icon-wenhao"></i>
              </el-tooltip>
            </template>
            <el-radio-group v-model="form.criticalVersionFlag">
              <!-- <el-radio :label="true">是</el-radio> -->
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="固件包" prop="package">
            <template #label>
              <span>固件包</span>&nbsp;
              <el-tooltip content="一般用于固件升级（OTA）的固件文件" placement="top">
                <i class="iconfont icon-wenhao"></i>
              </el-tooltip>
            </template>
            <el-upload
              class="upload-demo"
              action="/ota/v1/component/info/file/upload"
              :on-success="uploadSuccess"
              :headers="headerObj"
              :on-error="uploadError"
              :on-progress="uploadProgress"
              multiple
              :file-list="fileList">
              <el-button v-if="!uploadSuccessOrError" size="small" icon="el-icon-plus">上传固件</el-button>
              <div v-else>
                <el-input v-model="firmwarePackage.fileName" class="firmwareName" placeholder="已上传固件名字"></el-input>
                <!-- <div class="uploadInfo">
                  <el-row>
                    <el-col :span="12">
                      <span class="infoTitle">文件大小：</span>
                      <span class="infoVal">{{ bytesToMegabytes(firmwarePackage.length) }}字节</span>
                    </el-col>
                    <el-col :span="12">
                      <span class="infoTitle">版本号：</span>
                      <span class="infoVal">{{
                        firmwarePackage.version
                      }}</span>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="24">
                      <span class="infoTitle">模块类型：</span>
                      <span class="infoVal">{{ firmwarePackage.efirmwareName }}</span>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="24">
                      <span class="infoTitle">校验值（MD5）：</span>
                      <span class="infoVal">{{ firmwarePackage.md5 }}</span>
                    </el-col>
                  </el-row>
                </div> -->
              </div>
              <!-- <div slot="tip" class="el-upload__tip">16M以内</div> -->
            </el-upload>
            <el-progress
              v-if="isUploading"
              :percentage="uploadPercentage"
            ></el-progress>
          </el-form-item>
          <el-form-item label="版本说明" prop="description">
            <el-input
              v-model="form.description"
              type="textarea"
              maxlength="200"
              show-word-limit
              placeholder="请输入适当说明信息"></el-input>
          </el-form-item>
          <el-form-item label="是否上架" prop="isListed">
            <template #label>
              <span>是否上架</span>&nbsp;
              <el-tooltip content="上架操作后，才能进行固件升级和版本发布" placement="top">
                <i class="iconfont icon-wenhao"></i>
              </el-tooltip>
            </template>
            <el-radio-group v-model="form.isListed">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button size="14" @click="handleClose">取消</el-button>
      <el-button type="primary" size="14" @click="handleSubmit">保存</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { firmwareType, addFirmware } from "@/api/product/firmware"
import store from '@/store'
export default {
  name: "addFirmwareDialog",
  props: {
    pageType: {
      type: String,
      default: 'firmwareManage' // firmwareManage 固件管理 firmwareDetails 固件详情
    },
    queryFirmwareManageList: {
      type: Function,
      default: () => {} // 一个空函数，避免子组件调用时报错
    }
  },
  data() {
    const validatePackage = (rule, value, callback) => {
      if (this.fileList.length === 0) {
        callback(new Error('请上传固件'))
      } else {
        callback()
      }
    }
    return {
      dialogVisible: false, // 弹窗是否显示
      fileList: [], // 上传的固件文件
      uploadSuccessOrError: false, // 上传固件成功则展示固件基本信息否则不展示
      firmwarePackage: "", // 上传成功的固件包信息
      uploadLoading: '', // 上传固件弹窗的loading
      uploadPercentage: 0, // 上传进度百分比
      isUploading: false, // 是否正在上传
      headerObj: {
        'TENANT-ID': store.getters.userInfo.tenantId,
        Authorization: 'Bearer ' + store.getters.access_token
      },
      firmwareTypeOptions: [], // 固件类型选项
      form: {
        name: '', // 固件名称
        type: '', // 固件类型
        upgradeChannel: '', // 升级通道号
        customNumbering: 0, // 自定义编号
        timeoutTime: '', // 固件升级超时时间
        singleTimeout: '', // 单次超时时长
        remarks: '', // 备注说明
        version: '', // 固件版本
        criticalVersionFlag: false, // 关键版本
        package: '', // 固件包
        description: '', // 版本说明
        isListed: '' // 是否上架
      },
      // 生成1到180的数字数组作为选项
      upgradeChannelOptions: Array.from({ length: 180 }, (_, index) => index + 1),
      rules: {
        package: { required: true, validator: validatePackage, trigger: 'blur' },
        name: [
          { required: true, message: '请输入固件名称', trigger: 'blur' }
          // { min: 1, max: 32, message: '请输入规范的固件名称', trigger: 'blur' }
          // { validator: this.validateName, trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择固件类型', trigger: 'change' }
        ],
        upgradeChannel: [
          { required: true, message: '请选择升级通道号', trigger: 'change' }
        ],
        timeoutTime: [
          { required: true, message: '请输入固件升级超时时间', trigger: 'blur' },
          { validator: this.validateTimeoutTime, trigger: 'blur' }
        ],
        singleTimeout: [
          { required: true, message: '请输入单次超时时长', trigger: 'blur' }
          // { validator: this.validateSingleTimeout, trigger: 'blur' }
        ],
        version: [
          { required: true, message: '请输入固件版本', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getFirmwareType()
  },
  methods: {
    // 固件升级超时时间校验提示
    validateTimeoutTime(rule, value, callback) {
      const regex = /^(?:1[0-7]\d{2}|1800|[1-9]\d{0,2})$/
      if (!regex.test(value)) {
        callback(new Error('请输入正确的固件升级超时时间'))
      } else {
        callback()
      }
    },
    // 单次超时时长校验提示
    // validateSingleTimeout(rule, value, callback) {
    //   const regex = /^(?:1[0-1]\d|120|[1-9]\d?)$/
    //   if (!regex.test(value)) {
    //     callback(new Error('请输入正确的单次超时时长'))
    //   } else {
    //     callback()
    //   }
    // },
    // 获取固件类型
    getFirmwareType() {
      firmwareType().then(res => {
        this.firmwareTypeOptions = res.data.data
      }).catch(err => {
        this.$message.error(err || '请求异常')
      })
    },
    // // 字节单位转换为m
    // bytesToMegabytes(bytes) {
    //   const megabytes = parseInt(bytes) / (1024 * 1024)
    //   return megabytes.toFixed(4) + 'M'
    // },
    // 只能上传一个固件，超过替换
    handleChange(file, fileList) {
      // this.fileList = [file];
    },
    // 固件上传失败
    uploadError(err, file, fileList) {
      this.isUploading = false
      this.uploadPercentage = 0
      this.$message.error(err)
    },
    // 固件上传成功
    uploadSuccess(response, file, fileList) {
      if (response.code === 0) {
        this.fileList = [file]
        this.uploadSuccessOrError = true
        this.firmwarePackage = response.data
        this.isUploading = false
        this.uploadPercentage = 0
      } else {
        this.$message.error(response.msg)
        this.isUploading = false
        this.uploadPercentage = 0
      }
    },
    // 固件包上传时的钩子
    uploadProgress(event, file, fileList) {
      this.isUploading = true
      this.uploadPercentage = Math.floor(event.percent)
    },
    // 新建固件弹窗关闭
    handleClose() {
      this.dialogVisible = false
      this.$refs.form.resetFields()
      this.fileList = []
      this.uploadSuccessOrError = false
      this.firmwarePackage = {}
    },
    // 提交
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const params = {
            name: this.form.name,
            componentType: this.form.type,
            upgradeChannelNumber: this.form.upgradeChannel,
            customNumber: this.form.customNumbering,
            timeoutTime: this.form.timeoutTime,
            singleTimeout: this.form.singleTimeout,
            description: this.form.remarks,
            addFirmwareBO: {
              ...this.firmwarePackage,
              version: this.form.version,
              description: this.form.description,
              criticalVersionFlag: this.form.criticalVersionFlag,
              isListed: this.form.isListed
            }
          }
          this.uploadLoading = true
          addFirmware(params).then((res) => {
            this.tableData = res.data.data.records
            this.total = res.data.data.total
            this.$message.success('上传成功')
            this.handleClose()
            this.uploadLoading = false
            // 返回固件管理列表页调用父组件方法刷新列表
            if (this.pageType === 'firmwareManage') {
              this.queryFirmwareManageList()
            } else if (this.pageType === 'firmwareDetails') {
              this.$emit('refreshFirmwareList')
            }
          }).catch(err => {
            this.uploadLoading = false
            this.$message.error(err.message)
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.el-select {
  width: 100%;
}

::v-deep .upload-demo {
  .el-upload-list {
    display: none;
  }

  .el-upload {
    width: 100%;

    .el-button {
      color: #275fe8;
      width: 100%;
      font-size: 14px;
    }
  }
}
</style>

